<?php


namespace App\Services\Xml;


use Chumper\Zipper\Zipper;

class Xml
{
    private $xmlDoc;
    public function __construct()
    {
        $this->xmlDoc = new \DOMDocument('1.0','UTF-8');
    }

    /**
     * 设置xml
     * @param $param
     * @param null $node
     */
    public function createNode($param,$node = null){

        foreach ($param as $key=>$value) {

            if (is_array($value)) {

                if (!$node) {
                    $node = $newNode = $this->xmlDoc->createElement($key);
                    $this->xmlDoc->appendChild($node);
                } else {
                    $newNode = $this->xmlDoc->createElement($key);
                    $node->appendChild($newNode);
                }
                $this->createNode($value,$newNode);
                /*if ($key == 'productMark') {

                    foreach ($value as $pK=>$pV)  {

                        $node->setAttribute($key,$pV);
                    }

                } else {

                    $this->createNode($value,$newNode);
                }*/

            } else {

                $node->setAttribute($key,$value);
            }
        }

        return $node;
    }

    /**
     * 保存文件
     * @param $filename
     */
    public function saveXml($filename) {

        $this->xmlDoc->save($filename);
    }

    /**
     * 压缩文件
     * @param $filename
     * @param $desFilename
     * @throws \Exception
     */
    public function zip($filename,$zipFilename){

        $zipper = new Zipper();
        $zipper->make($zipFilename)
            ->add($filename)
            ->close();
    }
}